#!BPY
# encoding: utf-8

"""
Name: 'KISS CM3D camera motion (.bin)'
Blender: 249
Group: 'Export'
Tooltip: 'CM3D camera motion exporter'
"""

__author__ = 'Desuwa'
__version__ = '0.1'
__url__ = "http://code.google.com/p/anz2blend/"
__email__ = "desuwane@gmail.com"

"""
The MIT License

Copyright (c) 2011 Desuwa

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import Blender
import BPyMessages
import bpy
from Blender import BGL
from Blender.BGL import *
from struct import pack

CAMERANAME = "CM3DCamera"

#----------------
# BinaryWriter
#----------------
def writeSingle(f, w):
	data = pack("<f", f)
	w.write(data)

def writeInt(i, w):
	data = pack("<i", i)
	w.write(data)

#----------------
# GUI
#----------------
saveAs = Blender.Draw.Create("")
SCALEFACTOR = Blender.Draw.Create(10.0)

def getSaveAs(path):
	global saveAs
	if not BPyMessages.Warning_SaveOver(path):
		return
	if not path.lower().endswith(".bin"):
		path += ".bin"
	saveAs.val = path
	Blender.Draw.Redraw(1)

def guiEvent(event, value):	
	if event == Blender.Draw.ESCKEY:
		Blender.Draw.Exit()
		return

def guiButton(event):
	global saveAs
	if event == 1:
		Blender.Window.FileSelector(getSaveAs, "Save", Blender.sys.makename(ext = ".bin"))
	elif event == 666:
		if saveAs.val == "":
			return
		exportCamera()
		Blender.Draw.Exit()
	elif event == 999:
		Blender.Draw.Exit()
	
	Blender.Draw.Redraw(1)

def drawGui():
	global saveAs, SCALEFACTOR
	
	glClearColor(0.55, 0.57, 0.67, 1)
	glClear(BGL.GL_COLOR_BUFFER_BIT)
	
	glColor3f(0.70, 0.71, 0.85)
	glRasterPos2i(35, 40)
	Blender.Draw.Text("KISS Camera Importer " + __version__, "large")
	glRasterPos2i(35, 25)
	Blender.Draw.Text(__url__, "small")
	
	saveAs = Blender.Draw.String("Save as: ", 1, 35, 145, 315, 18, saveAs.val, 255)
	Blender.Draw.PushButton("Browse", 1, 355, 145, 55, 18, "")
	
	glColor3f(0.16, 0.168, 0.2)
	
	SCALEFACTOR = Blender.Draw.Number("Scale:", 3, 35, 115, 150, 18, SCALEFACTOR.val, 0, 100)
	glRasterPos2i(195, 120)
	Blender.Draw.Text("Scale the dimensions by SCALEFACTOR")
	
	Blender.Draw.PushButton("Export", 666, 35, 70, 75, 30, "")
	Blender.Draw.PushButton("Cancel", 999, 120, 70, 75, 30, "")

#----------------
# Main
#----------------
def exportCamera():
	global saveAs, SCALEFACTOR
	
	saveAs = saveAs.val
	SCALEFACTOR = 1.0 if SCALEFACTOR.val == 0 else SCALEFACTOR.val
	
	if not saveAs.lower().endswith(".bin"):
		saveAs += ".bin"
	
	print "======= Exporting Camera ======="
	STARTTIME = Blender.sys.time()
	
	Blender.Window.WaitCursor(1)
	
	scn = bpy.data.scenes.active
	
	startFrame = scn.getRenderingContext().startFrame()
	endFrame = scn.getRenderingContext().endFrame()
	frameCount = endFrame - startFrame + 1
	print "Frame count: %d" % (frameCount)
	
	try:
		camera = bpy.data.objects[CAMERANAME]
	except KeyError:
		raise Exception('You need a Camera object named "%s". Aborting.' % CAMERANAME)
	
	if len(camera.constraints) == 0:
		raise Exception("Camera must have a Track To constraint. Aborting")
	
	const = None
	for c in camera.constraints:
		if c.type != Blender.Constraint.Type.TRACKTO:
			continue
		else:
			const = c
	
	if const is None:
		raise Exception("Camera must have a Track To constraint. Aborting")
	
	try:
		if const[Blender.Constraint.Settings.TARGET] == None:
			raise KeyError
		tracker = const[Blender.Constraint.Settings.TARGET]
	except KeyError:
		raise Exception("The camera must track a valid object. Aborting")
	
	with open(saveAs, "wb") as w:
		writeInt(frameCount, w)
		
		writeInt(0, w)
		writeInt(0, w)
		writeInt(0, w)
		
		for frame in xrange(startFrame, endFrame + 1):
			Blender.Set('curframe', frame)
			
			# camera loc
			loc = camera.getLocation("worldspace")
			writeSingle(loc[0] * SCALEFACTOR, w) # X
			writeSingle(loc[2] * SCALEFACTOR, w) # Y
			writeSingle(loc[1] * SCALEFACTOR, w) # Z
			# fov
			writeSingle(35, w)
			
			writeSingle(0, w)
			writeSingle(1.0, w)
			writeSingle(0, w)
			writeSingle(0, w)
			
			# tracker loc
			loc = tracker.getLocation("worldspace")
			writeSingle(loc[0] * SCALEFACTOR, w) # X
			writeSingle(loc[2] * SCALEFACTOR, w) # Y
			writeSingle(loc[1] * SCALEFACTOR, w) # Z
			# junk?
			writeSingle(0, w)
	
	Blender.Window.WaitCursor(0)
	print "== Done, took %f seconds ==" % (Blender.sys.time() - STARTTIME)

#----------------
# Here it comes
#----------------
Blender.Draw.Register(drawGui, guiEvent, guiButton)

